package ua.kpi.flats.dao.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ua.kpi.flats.dao.MeetingDao;
import ua.kpi.flats.entity.Meeting;
import ua.kpi.flats.entity.enums.MeetingStatus;
import ua.kpi.flats.entity.enums.SuitableOptionsEnum;

@Repository("meetingDao")
public class MeetingDaoImpl extends HibernateDaoSupport implements MeetingDao {
	
	@Autowired
	public MeetingDaoImpl(HibernateTemplate hibernateTemplate) {
		super.setHibernateTemplate(hibernateTemplate);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW,
			       isolation = Isolation.READ_COMMITTED)
	public void create(Meeting meeting) {
		getHibernateTemplate().refresh(meeting.getOption());
		getHibernateTemplate().save(meeting);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(isolation = Isolation.READ_COMMITTED,
			       readOnly = true)
	public List<Meeting> getMeetings(long appId) {
		return getHibernateTemplate().find("SELECT m FROM Meeting m WHERE " +
				"m.option.application.id = ? ORDER BY m.id",appId);
	}
	
	@Transactional(isolation = Isolation.READ_COMMITTED)
    public void finish(Meeting meeting) {
		SuitableOptionsEnum status = meeting.getOption().getStatus();
		
		getHibernateTemplate().refresh(meeting);
		meeting.setStatus(MeetingStatus.FINISHED);		
		meeting.getOption().setStatus(status);
		
		getHibernateTemplate().update(meeting);
	}
	
	@Transactional(isolation = Isolation.READ_COMMITTED)
    public void delete(Meeting meeting) {
		getHibernateTemplate().refresh(meeting);
		getHibernateTemplate().delete(meeting);
	}
}
